package com.gimi.cloud.jimi.manage.controller.prod;

import com.gimi.cloud.jimi.common.enums.ResponseCodeEnum;
import com.gimi.cloud.jimi.common.utils.JsonUtil;
import com.gimi.cloud.jimi.common.utils.Page;
import com.gimi.cloud.jimi.common.utils.UUIDUtil;
import com.gimi.cloud.jimi.common.utils.oss.AliOSSUtil;
import com.gimi.cloud.jimi.common.utils.reqhead.Response;
import com.gimi.cloud.jimi.common.utils.reqhead.Util;
import com.gimi.cloud.jimi.dto.prod.ProdBrandDTO;
import com.gimi.cloud.jimi.dto.prod.ProdCatModelDTO;
import com.gimi.cloud.jimi.dto.prod.ProdCategoryDTO;
import com.gimi.cloud.jimi.manage.service.prod.BrandService;
import com.gimi.cloud.jimi.manage.service.prod.CategoryService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.*;

/**
 * Created by lixj on 2017/12/18.
 */
@RestController
@RequestMapping(value = "category")
public class CategoryController {
    private final CategoryService categoryService;
    private final BrandService brandService;

    @Autowired
    public CategoryController(CategoryService categoryService,BrandService brandService){
        this.categoryService = categoryService;
        this.brandService = brandService;
    }

    /**
     * 商品品类根据id查询操作
     * @param prodCategoryDTO
     * @param request
     * @param response
     */
    @RequestMapping(value = "/list")
    public void categoryList(@RequestBody ProdCategoryDTO prodCategoryDTO, HttpServletRequest request, HttpServletResponse response) {
        Response resp = new Response();
        List<ProdCategoryDTO> list = categoryService.getCategoryList();
        resp.setRes_data(list);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        Util.sendResponse(JsonUtil.toJson(resp), response);
    }

    /** 查询品类分页列表 */
    @RequestMapping(value = "/pageList")
    public void pageList(@RequestBody ProdCategoryDTO prodCategoryDTO, HttpServletResponse response) {
        Response resp = new Response();
        Page<ProdCategoryDTO> list = categoryService.getCategoryPageList(prodCategoryDTO);
        resp.setRes_data(list);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        Util.sendResponse(JsonUtil.toJSONStringWithDateFormatYYYYMMDDHHMMSS(resp), response);
    }

    /** 查询三级品类详情 */
    @RequestMapping(value = "/getThreeProdCatModel")
    public void getThreeProdCatModel(@RequestBody ProdCatModelDTO prodCatModelDTO, HttpServletResponse response) {
        Response resp = new Response();
        List<ProdCatModelDTO> list = categoryService.getThreeProdCatModel(prodCatModelDTO);
        PageInfo<ProdCatModelDTO> page = new PageInfo<>(list);
        resp.setRes_data(page);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        Util.sendResponse(JsonUtil.toJSONStringWithDateFormatYYYYMMDDHHMMSS(resp), response);
    }

//    /**
//     * 商品品类添加操作
//     * @param prodCategoryDTO
//     * @param request
//     * @param response
//     */
//    @RequestMapping(value = "/add")
//    @Transactional
//    public void categoryAdd(@RequestBody ProdCategoryDTO prodCategoryDTO, HttpServletRequest request, HttpServletResponse response) {
//        Response resp = new Response();
//        boolean temp = true;
//        String msg = "";
//        //校验级别和父类匹配
//        int parentLength = prodCategoryDTO.getParentCatId().length();
//        if(prodCategoryDTO.getCatGrade()==1 ){
//            if( parentLength !=1){
//                resp.setResponseCode(ResponseCodeEnum.ADD_PRODCATEGORY_IS_NOT_SURE);
//                Util.sendResponse(JsonUtil.toJson(resp), response);
//                return;
//            }
//        }else if (prodCategoryDTO.getCatGrade()==2 ){
//            if( parentLength !=2) {
//                resp.setResponseCode(ResponseCodeEnum.ADD_PRODCATEGORY_IS_NOT_SURE);
//                Util.sendResponse(JsonUtil.toJson(resp), response);
//                return;
//            }
//        }else {
//            if( parentLength !=5) {
//                resp.setResponseCode(ResponseCodeEnum.ADD_PRODCATEGORY_IS_NOT_SURE);
//                Util.sendResponse(JsonUtil.toJson(resp), response);
//                return;
//            }
//        }
//
//
//        //因业务变更，id不允许前端填写，由后台生成
//        //先查出库里最大值，然后加1即可.
//        //截取的开始长度分别为：1级1，2级3，3级6
//
//        //拼接0的位数
//        int length = 0;
//        //截取的开始长度
//        int subStart = 0;
//        if(prodCategoryDTO.getCatGrade()==1){
//            length = 2;
//            subStart = 1;
//        }else if(prodCategoryDTO.getCatGrade()==2){
//            length = 3;
//            subStart = 3;
//        }else{
//            length = 4;
//            subStart = 6;
//        }
//
//        String maxValue = categoryService.findMaxCatIdByGrade(prodCategoryDTO.getParentCatId(),subStart);
//        String newStr = "0";
//        if(!"0".equals(maxValue)){
//            newStr = maxValue.replaceFirst("^0*", "");
//        }
//
//        int maxV = new Integer(newStr)+1;
//        //新增方法，为不同的级别拼接上相应的0的个数
//
//        String id = frontCompWithZore(maxV,length);
//        //再将父级id拼接上(1级时不拼，其他拼接)
//        if(prodCategoryDTO.getCatGrade()>1){
//            id = prodCategoryDTO.getParentCatId()+id;
//        }
//        prodCategoryDTO.setProdCatId(id);
//        prodCategoryDTO.setIsDelete(0);
//        prodCategoryDTO.setVersion(0);
//        ResponseCodeEnum responseCodeEnum= categoryService.categoryAdd(prodCategoryDTO);
//        resp.setResponseCode(responseCodeEnum);
//        Util.sendResponse(JsonUtil.toJson(resp), response);
//    }

    @RequestMapping(value = "/saveOrUpdate")
    public void saveOrUpdate(HttpServletRequest request,HttpServletResponse response,@RequestBody ProdCategoryDTO prodCategoryDTO) throws Exception{
        Response resp = new Response();
        categoryService.saveOrUpdate(prodCategoryDTO);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED,"保存成功");
        Util.sendResponse(JsonUtil.toJson(resp), response);
    }

//    /**
//     * 商品品类更新操作
//     * @param prodCategoryDTO
//     * @param request
//     * @param response
//     */
//    @RequestMapping(value = "/update")
//    public void categoryUpdate(@RequestBody ProdCategoryDTO prodCategoryDTO, HttpServletRequest request, HttpServletResponse response) {
//        Response resp = new Response();
//        ResponseCodeEnum responseCodeEnum= categoryService.categoryUpdate(prodCategoryDTO);
//        resp.setResponseCode(responseCodeEnum);
//        Util.sendResponse(JsonUtil.toJson(resp), response);
//    }

    /**
     * 商品品类删除操作
     * @param prodCategoryDTO
     * @param request
     * @param response
     */
    @RequestMapping(value = "/delete")
    public void categoryDelete(@RequestBody ProdCategoryDTO prodCategoryDTO, HttpServletRequest request, HttpServletResponse response) {
        Response resp = new Response();
        if(categoryService.categoryDelete(prodCategoryDTO)){
            resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        }else{
            resp.setResponseCode(ResponseCodeEnum.PRODCATEGORY_IS_NOT_EXIT);
        }
        Util.sendResponse(JsonUtil.toJson(resp), response);
    }

//    @RequestMapping(value = "/gotoEditProdCategory")
//    public void gotoEditProdCategory(@RequestBody ProdCategoryDTO prodCategoryDTO, HttpServletResponse response) {
//        Response resp = new Response();
//        ProdCategoryDTO newprodCategoryDTO=categoryService.gotoEditProdCategory(prodCategoryDTO);
//        resp.setRes_data(newprodCategoryDTO);
//        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
//        Util.sendResponse(JsonUtil.toJson(resp), response);
//    }

    @RequestMapping(value = "/loadPordCategoryAndInitModelInfo")
    public void loadPordCategoryAndInitModelInfo(@RequestBody ProdCategoryDTO prodCategoryDTO, HttpServletResponse response) throws Exception{
        Response resp = new Response();
        ProdCategoryDTO prodCategory= categoryService.loadPordCategoryAndInitModelInfo(prodCategoryDTO,prodCategoryDTO.getProdCatId());
        Map<String,Object> resData = new HashMap<>();
        resData.put("prodCategory",prodCategory);
        resp.setRes_data(resData);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        Util.sendResponse(JsonUtil.toJSONStringWithDateFormatYYYYMMDDHHMMSS(resp), response);
    }


    /**
     * 根据参数查询出所有的对应商品品类列表
     * @param prodCategoryDTO
     * @param request
     * @param response
     */
    @RequestMapping(value = "/searchCategoryListByGrade")
    public void searchCategoryListByGrade(@RequestBody ProdCategoryDTO prodCategoryDTO, HttpServletRequest request, HttpServletResponse response) {
        Response resp = new Response();
        List<ProdCategoryDTO> ProdCategoryDTOList = categoryService.searchCategoryListByGrade(prodCategoryDTO.getCatGrade()-1);
        resp.setRes_data(ProdCategoryDTOList);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        Util.sendResponse(JsonUtil.toJSONStringWithDateFormatYYYYMMDDHHMMSS(resp), response);
    }
    /**
    * 将元数据前补零，补后的总长度为指定的长度，以字符串的形式返回
    * @param sourceDate
    * @param formatLength
    * @return 重组后的数据
    */
    public String frontCompWithZore(int sourceDate,int formatLength) {
        /*
    　　* 0 指前面补充零
    　　* formatLength 字符总长度为 formatLength
    　　* d 代表为正数。
    　　*/
    String newString = String.format("%0"+formatLength+"d", sourceDate);
    return newString;
    }
    
    /*************************品类图片上传****************************/
    /**
     * 品类logo图片上传
     */
    @RequestMapping(value = "/fileUpload")
    public void fileUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = "";
        StandardMultipartHttpServletRequest multipartHttpServletRequest = (StandardMultipartHttpServletRequest) request;
        MultiValueMap multipartFiles = multipartHttpServletRequest.getMultiFileMap();
        for(Object entry : multipartFiles.entrySet()){
            LinkedList<MultipartFile> lists = ((Map.Entry<String, LinkedList<MultipartFile>>) entry).getValue();
            for(MultipartFile file : lists){
                InputStream is = file.getInputStream();
                String uuId = UUIDUtil.get32UUID();
                String dirPath = "category";
                String[] originalFilenames = file.getOriginalFilename().split("\\.");
                String fileName = uuId + "." + originalFilenames[originalFilenames.length-1];
                String result = AliOSSUtil.uploadFile(is,dirPath,fileName);
                String tempUrl = AliOSSUtil.getFileUrl(result,new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 365 * 100));
                System.out.println("==========>上传结果：" + url);
                url += ","+tempUrl;
            }
        }
        Response resp = new Response();
        Map<String,String> data = new HashMap<>();
        data.put("url",url.equals("")?url:url.substring(1));
        resp.setRes_data(data);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        Util.sendResponse(JsonUtil.toJson(resp), response);
    }

    /**
     * 获得树形结构的商品品类列表
     * @param prodCategoryDTO
     * @param request
     * @param response
     */
    @RequestMapping(value = "/getCategoryListTree")
    public void getCategoryListTree(@RequestBody ProdCategoryDTO prodCategoryDTO, HttpServletRequest request, HttpServletResponse response) {
        Response resp = new Response();
        List<Map<String, Object>> dto = categoryService.getCategoryListTree(prodCategoryDTO);
        resp.setRes_data(dto);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        Util.sendResponse(JsonUtil.toJson(resp), response);
    }


    @RequestMapping(value = "getCategoryListByParent")
    public void getCategoryListByParent(@RequestBody ProdCategoryDTO prodCategoryDTO, HttpServletResponse response){
        Response resp = new Response();
        List<ProdCategoryDTO> list = categoryService.getCategoryListByParent(prodCategoryDTO);
        if(list == null){
            list = new ArrayList<>();
        }
        resp.setRes_data(list);
        resp.setResponseCode(ResponseCodeEnum.SUCCESSED);
        Util.sendResponse(JsonUtil.toJson(resp), response);
    }
}
